﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Project_2._2.Models;
using Project_2._2.ViewModels;
using System.IO;
using Project_2._2.Extra;
using System.Web.Security;
using PagedList;
using PagedList.Mvc;

namespace Project_2._2.Controllers
{
    public class AdminCarsController : Controller
    {
        private QuanLyThueXeEntities db = new QuanLyThueXeEntities();
        private Common cm = new Common();
        #region Default
        // GET: /Adminrole/
        public ActionResult Default(int? page, string rd, string Record, string key, string SBy, string SType)
        {

            try
            {
                if (!Request.IsAuthenticated)
                {
                    return RedirectToAction("Login", "Admin");
                }
                else
                {
                    if (cm.CheckUserType(User.Identity.Name))
                    {
                        if (rd != null)
                        {
                            int soDong = int.Parse(rd);
                            string k = key;
                            string b = SBy;
                            string t = SType;
                            IPagedList<Xe> cars = null;
                            if (!string.IsNullOrEmpty(k) && b != "0")
                            {
                                ViewBag.Key = k;
                                ViewBag.SBy = b;
                                ViewBag.SType = t;

                                switch (b)
                                {
                                    case "Name":
                                        if (t == "1")
                                            cars = (from p in db.Xes where p.TenXe.Contains(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                                        else
                                        {
                                            cars = (from p in db.Xes where p.TenXe.Equals(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                                        }
                                        break;
                                    case "DongXe":
                                        if (t == "1")
                                            cars = (from p in db.Xes where p.DongXe.Contains(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                                        else
                                        {
                                            cars = (from p in db.Xes where p.DongXe.Equals(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                                        }
                                        break;
                                    case "DoiXe":
                                        if (t == "1")
                                            cars = (from p in db.Xes where p.DoiXe.Contains(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                                        else
                                        {
                                            cars = (from p in db.Xes where p.DoiXe.Equals(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                                        }
                                        break;
                                }
                            }
                            else
                            {
                                cars = (from p in db.Xes where p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                            }

                            ViewBag.record = rd;
                            return View(cars);
                        }
                        else
                        {
                            var cars = (from p in db.Xes where p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, 10);
                            return View(cars);
                        }
                    }
                    else
                        return RedirectToAction("Login", "Admin");
                }
            }
            catch (Exception)
            {
                return RedirectToAction("SystemErrors", "Default");
            }
        }
        //POST
        [HttpPost]
        public ActionResult Default(FormCollection col, int? page)
        {
            try
            {
                int soDong = int.Parse(col["soDong"]);
                string SearchBy = col["SearchBy"];
                string SearchType = col["SearchType"];
                string key = col["KeyWorld"];
                IPagedList<Xe> cars = null;

                //
                ViewBag.Key = key;
                ViewBag.SBy = SearchBy;
                ViewBag.SType = SearchType;
                ViewBag.record = soDong.ToString();

                if (string.IsNullOrEmpty(key))
                {
                    cars = (from p in db.Xes where p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                    return View(cars);
                }
                else
                {

                    switch (SearchBy)
                    {

                        case "Name":
                            if (SearchType == "1")
                                cars = (from p in db.Xes where p.TenXe.Contains(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                            else
                            {
                                cars = (from p in db.Xes where p.TenXe.Equals(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                            }
                            break;
                        case "DoiXe":
                            if (SearchType == "1")
                                cars = (from p in db.Xes where p.DoiXe.Contains(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                            else
                            {
                                cars = (from p in db.Xes where p.DoiXe.Equals(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                            }
                            break;
                        case "DongXe":
                            if (SearchType == "1")
                                cars = (from p in db.Xes where p.DongXe.Contains(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                            else
                            {
                                cars = (from p in db.Xes where p.DongXe.Equals(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                            }
                            break;
                        default:
                            ViewBag.erorr = "Không có dữ liệu .... ";
                            break;
                    }
                    return View(cars);
                }
            }
            catch (Exception)
            {
                return RedirectToAction("SystemErrors", "Default");
            }

        }
        #endregion
        public ActionResult Insert()
        {
            if (!Request.IsAuthenticated)
            {
                return RedirectToAction("Login", "Admin");
            }
            else
            {
                if (cm.CheckUserType(User.Identity.Name))
                {
                    return View();
                }
                else
                    return RedirectToAction("Login", "Admin");
            }
        }
        [HttpPost]
        public ActionResult Insert(CarList_ViewModel Cars, HttpPostedFileBase uploadFile)
        {
            if (!Request.IsAuthenticated)
            {
                return RedirectToAction("Login", "Admin");
            }
            else
            {
                try
                {
                    if (ModelState.IsValid)
                    {
                        if (Cars.captcha.CompareTo(Session["Captcha"]) != 0)
                            ModelState.AddModelError("Captcha", "Mã xác nhận không chính xác.");
                        else
                        {

                            Xe car = new Xe();
                            var fileName = "";
                            GiaXe giaxe = new GiaXe();
                            var idperson = (from p in db.People where p.TenDangNhap == User.Identity.Name select p).FirstOrDefault();
                            if (uploadFile != null && uploadFile.ContentLength > 0)
                            {
                                fileName = Path.GetFileName(uploadFile.FileName);
                                var path = Path.Combine(Server.MapPath("~/Images/Cars/"), fileName); uploadFile.SaveAs(path);

                            }
                            car.HinhAnhDaiDien = fileName.ToString();
                            car.PersonId = idperson.PersonId;
                            car.ThuongHieuId = Cars.ThuongHieuID;
                            car.LoaiXeId = Cars.LoaiID;
                            car.TenXe = Cars.name;
                            car.DoiXe = Cars.DoiXe;
                            car.DongXe = Cars.DongXe;
                            car.TaiXe = Cars.Taixe;
                            car.MauXe = Cars.Color;
                            car.PhuTroNgoaiGio = Cars.PhuTroNgoaiGio;
                            car.PhuTroQuaKm = Cars.PhuTroKM;
                            car.SuDungCuoiTuan = Cars.SuDungCuoiTuan;
                            car.ChiTiet = HttpUtility.HtmlDecode(Cars.ChiTiet);
                            car.Video = HttpUtility.HtmlDecode(Cars.Video);
                            car.TrangThai = Cars.TThai;
                            car.Duyet = true;
                            car.isDelete = false;
                            db.Xes.Add(car);
                            db.SaveChanges();

                            var idxe = (from p in db.Xes select p).Take(1).OrderByDescending(m => m.XeId).FirstOrDefault();

                            giaxe.DichVuId = Cars.dichvuID;
                            giaxe.XeId = idxe.XeId;
                            giaxe.Gia = Cars.Gia;
                            giaxe.isDelete = false;
                            db.GiaXes.Add(giaxe);
                            db.SaveChanges();
                            return RedirectToAction("Default", "AdminCars");
                        }
                    }
                    else
                    {
                        return View();
                    }
                }
                catch (Exception)
                {
                    return RedirectToAction("SystemErrors", "Default");
                }

            }
            return View();
        }
        public ActionResult Update(int id)
        {
            CarList_ViewModel carslist = new CarList_ViewModel();
            if (!Request.IsAuthenticated)
            {
                return RedirectToAction("Login", "Admin");
            }
            else
            {
                if (cm.CheckUserType(User.Identity.Name))
                {
                    try
                    {

                        var cars = (from xe in db.Xes
                                    join kh in db.People on xe.PersonId equals kh.PersonId
                                    join gia in db.GiaXes on xe.XeId equals gia.XeId
                                    join dv in db.DichVuThueXes on gia.DichVuId equals dv.DichVuId
                                    join loai in db.LoaiXes on xe.LoaiXeId equals loai.LoaiXeId
                                    join th in db.ThuongHieux on xe.ThuongHieuId equals th.ThuongHieuId

                                    where xe.XeId == id && xe.isDelete == false
                                    select new
                                    {
                                        id = xe.XeId,
                                        name = xe.TenXe,
                                        THieuID = th.ThuongHieuId,
                                        tenloai = loai.TenLoaiXe,
                                        tenhieu = th.TenThuongHieu,
                                        Doixe = xe.DoiXe,
                                        DongXe = xe.DongXe,
                                        Color = xe.MauXe,
                                        LoaiID = loai.LoaiXeId,
                                        khID = kh.PersonId,
                                        tenKH = kh.HoTen,
                                        Gia = gia.Gia,
                                        Hinh = xe.HinhAnhDaiDien,
                                        TThai = xe.TrangThai,
                                        tenDV = dv.TenDichVu,
                                        iddv = dv.DichVuId,
                                        chitiet = xe.ChiTiet,
                                        phutroKM = xe.PhuTroQuaKm,
                                        phutroNgoaiGio = xe.PhuTroNgoaiGio,
                                        sudungcuoituan = xe.SuDungCuoiTuan,
                                        hinhanhdaidien = xe.HinhAnhDaiDien,
                                        video = xe.Video,
                                        trangthai = xe.TrangThai,
                                        duyet = xe.Duyet,

                                    }).FirstOrDefault();

                                    carslist.id = cars.id;
                                    carslist.name = cars.name;
                                    carslist.ThuongHieuID = cars.THieuID;
                                    carslist.Loai = cars.tenloai;
                                    carslist.THieu = cars.tenhieu;
                                    carslist.DoiXe = cars.Doixe;
                                    carslist.DongXe = cars.DongXe;
                                    carslist.Color = cars.Color;
                                    carslist.LoaiID = cars.LoaiID;
                                    carslist.TThai = cars.TThai;
                                    carslist.Gia = cars.Gia;
                                    carslist.khachHangID = cars.khID;
                                    carslist.TenKH = cars.tenKH;
                                    carslist.hinh = cars.Hinh;
                                    carslist.dichvuID = cars.iddv;
                                    carslist.tendichvu = cars.tenDV;
                                    carslist.ChiTiet = cars.chitiet;
                                    carslist.PhuTroKM = cars.phutroKM;
                                    carslist.PhuTroNgoaiGio = cars.phutroNgoaiGio;
                                    carslist.SuDungCuoiTuan = cars.sudungcuoituan;
                                    carslist.Video = cars.video;
                                    carslist.TThai = cars.trangthai;
                                    carslist.duyet = cars.duyet;
                                    carslist.hinh = cars.hinhanhdaidien;

                        return View(carslist);
                    }
                    catch (Exception)
                    {
                        return RedirectToAction("SystemErrors", "Default");
                    }
                }
                else
                    return RedirectToAction("Login", "Admin");
            }
       
        }
        [HttpPost]
        public ActionResult Update(CarList_ViewModel Cars, HttpPostedFileBase uploadFile)
        {
            if (!Request.IsAuthenticated)
            {
                return RedirectToAction("Login", "Admin");
            }
            else
            {
                try
                {
                    if (ModelState.IsValid)
                    {
                        if (Cars.captcha.CompareTo(Session["Captcha"]) != 0)
                            ModelState.AddModelError("Captcha", "Mã xác nhận không chính xác.");
                        else
                        {

                            var car = (from p in db.Xes where p.XeId == Cars.id select p).FirstOrDefault();

                            var giaxe = (from p in db.GiaXes where p.XeId == Cars.id select p).FirstOrDefault();

                            var idperson = (from p in db.People where p.TenDangNhap == User.Identity.Name select p).FirstOrDefault();

                            var fileName = car.HinhAnhDaiDien;

                            if (uploadFile != null && uploadFile.ContentLength > 0)
                            {
                                fileName = Path.GetFileName(uploadFile.FileName);
                                var path = Path.Combine(Server.MapPath("~/Images/Cars/"), fileName); uploadFile.SaveAs(path);
                            }

                            car.HinhAnhDaiDien = fileName.ToString();
                            car.PersonId = idperson.PersonId;
                            car.ThuongHieuId = Cars.ThuongHieuID;
                            car.LoaiXeId = Cars.LoaiID;
                            car.TenXe = Cars.name;
                            car.DoiXe = Cars.DoiXe;
                            car.DongXe = Cars.DongXe;
                            car.TaiXe = Cars.Taixe;
                            car.MauXe = Cars.Color;
                            car.PhuTroNgoaiGio = Cars.PhuTroNgoaiGio;
                            car.PhuTroQuaKm = Cars.PhuTroKM;
                            car.SuDungCuoiTuan = Cars.SuDungCuoiTuan;
                            car.ChiTiet = HttpUtility.HtmlDecode(Cars.ChiTiet);
                            car.Video = HttpUtility.HtmlDecode(Cars.Video);
                            car.TrangThai = Cars.TThai;
                            car.Duyet = true;
                            car.isDelete = false;
                            UpdateModel(car);
                            db.SaveChanges();

                            giaxe.DichVuId = Cars.dichvuID;
                            giaxe.XeId = Cars.id;
                            giaxe.Gia = Cars.Gia;
                            giaxe.isDelete = false;
                            UpdateModel(giaxe);
                            db.SaveChanges();
                            return RedirectToAction("Default", "AdminCars");
                        }
                    }
                    else
                    {
                        return View();
                    }
                }
                catch (Exception)
                {
                    return RedirectToAction("SystemErrors", "Default");
                }

            }
            return View();
        }
        public ActionResult Details(int id)
        {
            CarList_ViewModel carslist = new CarList_ViewModel();
            if (!Request.IsAuthenticated)
            {
                return RedirectToAction("Login", "Admin");
            }
            else
            {
                if (cm.CheckUserType(User.Identity.Name))
                {
                    try
                    {

                        var cars = (from xe in db.Xes
                                    join kh in db.People on xe.PersonId equals kh.PersonId
                                    join gia in db.GiaXes on xe.XeId equals gia.XeId
                                    join dv in db.DichVuThueXes on gia.DichVuId equals dv.DichVuId
                                    join loai in db.LoaiXes on xe.LoaiXeId equals loai.LoaiXeId
                                    join th in db.ThuongHieux on xe.ThuongHieuId equals th.ThuongHieuId

                                    where xe.XeId == id && xe.isDelete == false
                                    select new
                                    {
                                        id = xe.XeId,
                                        name = xe.TenXe,
                                        THieuID = th.ThuongHieuId,
                                        tenloai = loai.TenLoaiXe,
                                        tenhieu = th.TenThuongHieu,
                                        Doixe = xe.DoiXe,
                                        DongXe = xe.DongXe,
                                        Color = xe.MauXe,
                                        LoaiID = loai.LoaiXeId,
                                        khID = kh.PersonId,
                                        tenKH = kh.HoTen,
                                        Gia = gia.Gia,
                                        Hinh = xe.HinhAnhDaiDien,
                                        TThai = xe.TrangThai,
                                        tenDV = dv.TenDichVu,
                                        iddv = dv.DichVuId,
                                        chitiet = xe.ChiTiet,
                                        phutroKM = xe.PhuTroQuaKm,
                                        phutroNgoaiGio = xe.PhuTroNgoaiGio,
                                        sudungcuoituan = xe.SuDungCuoiTuan,
                                        hinhanhdaidien = xe.HinhAnhDaiDien,
                                        video = xe.Video,
                                        trangthai = xe.TrangThai,
                                        duyet = xe.Duyet,

                                    }).ToList();

                        foreach (var item in cars)
                        {
                            carslist.id = item.id;
                            carslist.name = item.name;
                            carslist.ThuongHieuID = item.THieuID;
                            carslist.Loai = item.tenloai;
                            carslist.THieu = item.tenhieu;
                            carslist.DoiXe = item.Doixe;
                            carslist.DongXe = item.DongXe;
                            carslist.Color = item.Color;
                            carslist.LoaiID = item.LoaiID;
                            carslist.TThai = item.TThai;
                            carslist.Gia = item.Gia;
                            carslist.khachHangID = item.khID;
                            carslist.TenKH = item.tenKH;
                            carslist.hinh = item.Hinh;
                            carslist.dichvuID = item.iddv;
                            carslist.tendichvu = item.tenDV;
                            carslist.ChiTiet = item.chitiet;
                            carslist.PhuTroKM = item.phutroKM;
                            carslist.PhuTroNgoaiGio = item.phutroNgoaiGio;
                            carslist.SuDungCuoiTuan = item.sudungcuoituan;
                            carslist.Video = item.video;
                            carslist.TThai = item.trangthai;
                            carslist.duyet = item.duyet;
                            carslist.hinh = item.hinhanhdaidien;
                        }

                        return View(carslist);
                    }
                    catch (Exception)
                    {
                        return RedirectToAction("SystemErrors", "Default");
                    }
                }
                else
                    return RedirectToAction("Login", "Admin");
            }
           
        }
        public ActionResult Delete(int id)
        {
            if (!Request.IsAuthenticated)
            {
                return RedirectToAction("Login", "Admin");
            }
            else
            {
                if (cm.CheckUserType(User.Identity.Name))
                {
                    try
                    {
                        Xe car = (from p in db.Xes where p.XeId == id select p).First();
                        car.isDelete = true;
                        UpdateModel(car);
                        db.SaveChanges();
                        return RedirectToAction("Default", "AdminCars");
                    }
                    catch (Exception)
                    {
                        return RedirectToAction("SystemErrors", "Default");
                    }

                }
                else
                    return RedirectToAction("Login", "Admin");
            }
        }
        public ActionResult Accept(int id) 
        {
            if (!Request.IsAuthenticated)
            {
                return RedirectToAction("Login", "Admin");
            }
            else
            {
                if (cm.CheckUserType(User.Identity.Name))
                {
                    try
                    {
                        Xe car = (from p in db.Xes where p.XeId == id select p).First();
                        car.Duyet = true;
                        UpdateModel(car);
                        db.SaveChanges();
                        return RedirectToAction("Default", "AdminCars");
                    }
                    catch (Exception)
                    {
                        return RedirectToAction("SystemErrors", "Default");
                    }

                }
                else
                    return RedirectToAction("Login", "Admin");
            }
        }
       
        [HttpPost]
        public ActionResult Multi_Delete(IEnumerable<int> XeIdsToDelete)
        {
            if (!Request.IsAuthenticated)
            {
                return RedirectToAction("Login", "Admin");
            }
            else
            {
                if (cm.CheckUserType(User.Identity.Name))
                {
                    try
                    {
                        var Xe_delete = db.Xes.Where(x => XeIdsToDelete.Contains(x.XeId)).ToList();
                        foreach (var car in Xe_delete)
                        {
                            car.isDelete = true;
                            UpdateModel(car);
                            db.SaveChanges();
                        }
                        return RedirectToAction("Default", "AdminCars");
                    }
                    catch (Exception)
                    {
                        return RedirectToAction("SystemErrors", "Default");
                    }
                }
                else
                    return RedirectToAction("Login", "Admin");
            }

        }
      
    }
}
